import Vue from 'vue'
import VueRouter from 'vue-router'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: () => import('../views/MyLogin') },
  { path: '/myblog', component: () => import('../views/MyBlog'), children: [] },
  { path: '/viewblog',name:'viewblog', component: () => import('../views/MyBlog/ViewBlog')},
  {
    path: '/admin',
    component: () => import('../views/MyAdmin'),
    redirect: '/admin/home',
    children: [
      { path: 'home', component: () => import('../views/MyAdmin/MyHome') },
      { path: 'user', component: () => import('../views/MyAdmin/MyUser') },
      { path: 'category', component: () => import('../views/MyAdmin/MyCategory') },
      { path: 'article', component: () => import('../views/MyAdmin/MyArticle') },
      { path: '/article/add', component: () => import('../views/MyAdmin/MyArticle/ArticleAdd') },
      { path: '/user/add', component: () => import('../views/MyAdmin/user/AddUser') },
      { path: '/article/editor', name: 'editor', component: () => import('../views/MyAdmin/MyArticle/ArticleEditor') },
      { path: '/user/editor', name: 'usereditor', component: () => import('../views/MyAdmin/user/UserEditor') },
      { path: 'leavewords', component: () => import('../views/MyAdmin/LeaveWords') }
    ]
  },
  { path: '/', redirect: '/admin/home' },
  { path: '*', component: () => import('../views/NotFound') }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token')
  let ismanager = localStorage.getItem('ismanager')
  if (token) {
    if (to.path == '/myblog' || to.path == '/login'||to.path=='/viewblog') {
      next()
    } else {
      if (ismanager == '1') {
        next()
      } else {
        next('/myblog')
        Message({
          type: 'error',
          message: '没有权限',
          showClose: true,
          duration: 1000
        })
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      Message({
        type: 'error',
        message: '请先登录',
        showClose: true,
        duration: 1000
      })
      next('/login')
    }
  }
})
export default router
